package net.kqinfo.core.controller.management;

import java.util.ArrayList;
import java.util.List;

import net.kqinfo.core.controller.management.condition.OrganizationCondition;
import net.kqinfo.core.model.Organization;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;
import com.jfinal.plugin.activerecord.Page;

public class OrganizationController extends Controller{
	
	public OrganizationCondition cond;
	
	private static final String CREATE = "/WEB-INF/views/management/security/organization/create.html";
	private static final String UPDATE = "/WEB-INF/views/management/security/organization/update.html";
	private static final String LIST = "/WEB-INF/views/management/security/organization/list.html";
	private static final String TREE = "/WEB-INF/views/management/security/organization/tree.html";

	public void index(){
		long id = getParaToInt(0,1);
		setAttr("organization", Organization.dao.findById(id));
		renderNull();
	}
	
	@Before(OrganizationCondition.class)
	public void list(){
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		cond.buildSql(sql, paras);
		Page<Organization> page= Organization.dao.paginate(cond.getPageNumber(), cond.getPageSize(), "select * ", sql.toString(),paras.toArray());
		setAttr("page", page);
		render(LIST);
	}
	
	@Before(OrganizationCondition.class)
	public void create(){
		render(CREATE);
	}
	
	public void doCreate(){
		Organization organization = getModel(Organization.class);
		organization.save();
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void update(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要修改的组织。"));
		}else{
			setAttr("organization", Organization.dao.findById(id));
		}
		render(UPDATE);
	}
	
	public void doUpdate(){
		Organization organization = getModel(Organization.class);
		organization.update();
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void delete(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要删除的组织。"));
		}else{
			Organization.dao.deleteById(id);
		}
		render(DwzRender.success());
	}
	
	public void tree(){
		Organization organization = Organization.dao.findById(1);
		setAttr("organization", organization);
		render(TREE);
	}

	public OrganizationCondition getCond() {
		return cond;
	}

	public void setCond(OrganizationCondition cond) {
		this.cond = cond;
	}
	
}
